#!/usr/bin/env python
# --*-- encoding:utf-8 --*-- 

from django.http import HttpResponse,HttpResponseRedirect

from fetion.models import FetionStatus,SMSQueue
from fetion.models import FETION_STATUS_ENUM
from api.models import SMSLog

from django.utils import simplejson as json

import datetime


def query_img(request,phone,security):
    u'''查询飞信是否在线
    '''
    color = "hong"
    status = __get_fetion_status(phone,security)
    if status:
        if status.status == FETION_STATUS_ENUM[0][0]:
            color = "lv"
    return HttpResponseRedirect("http://%s/static/api/imgs/deng-%s.png"%(request.META['HTTP_HOST'],color))

def query_info(request,phone,security):
    status = __get_fetion_status(phone,security)
    if status:
        return HttpResponse(json.dumps({"status":status.status}))
    return HttpResponse(status=400)


SMS_TIME_LIMIT = 10 #默认60*5秒
def post_sms(request,phone,security):
    u'''发送短信API.给自己发
    '''
    status = __get_fetion_status(phone,security)
    if status and status.receiver:
        #时间检测,限制{SMS_TIME_LIMIT}分钟一条
        now = datetime.datetime.now()
        ip = request.META['REMOTE_ADDR']
        
        flg = False
        logs = SMSLog.objects.filter(phone=phone,ip=ip)
        if logs and len(logs)>0:
            log = logs[0]
            last_time = log.time
            #比较当前时间
        
        msg = request.POST.get('msg',None)
        if msg and flg:
            #加入队列
            sms_queue = SMSQueue()
            sms_queue.phone = phone
            sms_queue.receiver = status.receiver
            sms_queue.msg = msg
            sms_queue.save()
            #保存日志
            sms_log = SMSLog()
            sms_log.phone = phone
            sms_log.ip = ip
            sms_log.receiver = status.receiver
            sms_log.save()
            #
            return HttpResponse(json.dumps({"success":True}))
    return HttpResponse(json.dumps({"success":False}))

#--------------内部方法---------------------

def __get_fetion_status(phone,security):
    status = FetionStatus.objects.filter(phone=phone,security=security)
    if status and len(status)>0:
        return status[0]
    return None


    